package com.xiaoKe.zhonghzu.ui.fzxz;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.xiaoKe.zhonghzu.R;
import com.xiaoKe.zhonghzu.databinding.FragmentReproductiveAddBinding;
import com.xiaoKe.zhonghzu.global.base.VeinRouter;
import com.xiaoKe.zhonghzu.global.bean.ClFzData;
import com.xiaoKe.zhonghzu.global.bean.FzDataListBean;
import com.xiaoKe.zhonghzu.global.bean.FzDataObject;
import com.xiaoKe.zhonghzu.global.okhttp.ApiCallback;
import com.xiaoKe.zhonghzu.global.okhttp.ApiCallbackOnResponse;
import com.xiaoKe.zhonghzu.global.okhttp.ApiService;
import com.xiaoKe.zhonghzu.global.okhttp.RetrofitClient;
import com.xiaoKe.zhonghzu.global.tool.DateUtils;
import com.xiaoKe.zhonghzu.global.tool.PvOptions;
import com.xiaoKe.zhonghzu.global.tool.SPUtils;
import com.xiaoKe.zhonghzu.global.view.ViewTotHeader;
import com.xiaoKe.zhonghzu.ui.gather.CodeFragment;
import com.xiaoKe.zhonghzu.ui.onClick.NoDoubleClickListener;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @ProjectName : xiaoke-pad-zhongzhu
 * @Author : Shijingna
 * @Time : 2024/11/29 11:13
 * @Description : 文件描述
 */
public class ReproductiveAddFragment extends CodeFragment<FragmentReproductiveAddBinding> {
    ClFzData clFzData;
    String type;
    List<String> farrowingMethodList = new ArrayList<>();

    @Override
    protected void initView() {


        farrowingMethodList.add("顺产");
        farrowingMethodList.add("早产");
        farrowingMethodList.add("难产");
        super.initView();
        clFzData = (ClFzData) getArguments().getSerializable("data");
        if (null == clFzData) { //手动记录
            type = "post";
            clFzData = new ClFzData();
        } else if (clFzData.getInputType() == 1 && 0 == clFzData.getId()) { //扫码记录
            type = "post";
            binding.collectionDate.setText(LocalDate.now().toString());
            binding.pigCode.setText(DateUtils.getContent(clFzData.getPigCode()));
            binding.pigBreed.setText(DateUtils.getContent(clFzData.getPigBreed()));
            binding.collectLocation.setText(DateUtils.getContent(clFzData.getCollectLocation()));
            binding.penNumber.setText(DateUtils.getContent(clFzData.getPenNo()));
            // 限制编辑
            restrictTextView(binding.pigCode);
            restrictTextView(binding.pigBreed);
            restrictTextView(binding.collectionDate);
            restrictTextView(binding.penNumber);
        } else { //修改
            type = "put";
            binding.houseNo.setText(DateUtils.getContent(clFzData.getHouseNo()));
            binding.pigCode.setText(DateUtils.getContent(clFzData.getPigCode()));
            binding.pigBreed.setText(DateUtils.getContent(clFzData.getPigBreed()));
            binding.collectionDate.setText(DateUtils.getContent(clFzData.getCollectDate()));
            binding.collectLocation.setText(DateUtils.getContent(clFzData.getCollectLocation()));
            binding.collector.setText(DateUtils.getContent(clFzData.getCollector()));
            binding.penNumber.setText(DateUtils.getContent(clFzData.getPenNo()));
            binding.farrowingDate.setText(DateUtils.getContent(clFzData.getFarrowDate()));
            binding.totalBorn.setText(DateUtils.getContent(clFzData.getTotalBorn()));
            binding.liveBorn.setText(DateUtils.getContent(clFzData.getLiveBorn()));
            binding.weakPiglet.setText(DateUtils.getContent(clFzData.getWeakPiglet()));
            binding.abnormal.setText(DateUtils.getContent(clFzData.getAbnormal()));
            binding.mummified.setText(DateUtils.getContent(clFzData.getMummified()));
            binding.deadPiglet.setText(DateUtils.getContent(clFzData.getDeadPiglet()));
            binding.live12h.setText(DateUtils.getContent(clFzData.getLive12h()));
            binding.live24h.setText(DateUtils.getContent(clFzData.getLive24h()));
            binding.live7d.setText(DateUtils.getContent(clFzData.getLive7d()));
            binding.weanWeight.setText(DateUtils.getContent(clFzData.getWeanWeight()));
            binding.weanPiglets.setText(DateUtils.getContent(clFzData.getWeanPiglets()));
            binding.rearedPiglets.setText(DateUtils.getContent(clFzData.getRearedPiglets()));
            binding.weight21d.setText(DateUtils.getContent(clFzData.getWeight21d()));
            binding.weight60d.setText(DateUtils.getContent(clFzData.getWeight60d()));
            binding.teatLeft.setText(DateUtils.getContent(clFzData.getTeatLeft()));
            binding.teatRight.setText(DateUtils.getContent(clFzData.getTeatRight()));
            binding.teatTotal.setText(DateUtils.getContent(clFzData.getTeatTotal()));
            binding.healthyPiglets.setText(DateUtils.getContent(clFzData.getHealthyPiglets()));
            binding.birthWeight.setText(DateUtils.getContent(clFzData.getBirthWeight()));
            binding.survivalRate.setText(DateUtils.getContent(clFzData.getSurvivalRate()));
            binding.firstFarrowAge.setText(DateUtils.getContent(clFzData.getFirstFarrowAge()));
            binding.parity.setText(DateUtils.getContent(clFzData.getParity()));
            binding.birthWeanWeight.setText(DateUtils.getContent(clFzData.getBirthWeanWeight()));

        }
        ViewTotHeader viewTotHeader = getView().findViewById(R.id.viewTotHeader);
        viewTotHeader.into("数据信息", false);
    }

    // 可封装为工具方法
    private void restrictTextView(TextView textView) {
        textView.setFocusable(false);
        textView.setFocusableInTouchMode(false);
        textView.setClickable(false);
        textView.setLongClickable(false);
        textView.setCursorVisible(false);
    }

    @Override
    protected void initData() {
        super.initData();
        NoDoubleClickListener noDoubleClickListener = new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View view) {
                switch (view.getId()) {
                    case R.id.addTv:
                        setData();
                        List<ClFzData> dtjFragmentList = SPUtils.getDataList("DtjFragment", ClFzData.class);
                        if (null != dtjFragmentList) { //先删除重复的替换上最新数据
                            dtjFragmentList.removeIf(fragment ->
                                    Objects.equals(fragment.getPigCode(), clFzData.getPigCode()) &&
                                            Objects.equals(fragment.getPigBreed(), clFzData.getPigBreed())
                            );
                        } else {
                            dtjFragmentList = new ArrayList<>();
                        }
                        dtjFragmentList.add(clFzData);
                        SPUtils.putDataList("DtjFragment", dtjFragmentList);
                        toFragmentPage(VeinRouter.DTJFRAGMENT);
                        getActivity().finish();
                        break;
                    case R.id.submit:
                        getData();
                        break;
                    case R.id.collectionDateRelativeLayout: //日期
                        PvOptions.showDatePicker(getContext(), new PvOptions.OnDateSelectedListener() {
                            @Override
                            public void onDateSelected(String date) {
                                binding.collectionDate.setText(date);
                                clFzData.setCollectDate(date);
                            }
                        });
                        break;
                    case R.id.farrowingDateRelativeLayout: //产仔日期
                        PvOptions.showDatePicker(getContext(), new PvOptions.OnDateSelectedListener() {
                            @Override
                            public void onDateSelected(String date) {
                                binding.farrowingDate.setText(date);
                                clFzData.setFarrowDate(date);
                            }
                        });
                        break;
                    case R.id.farrowingMethodRelativeLayout: //分娩方式
                        OptionsPickerView optionsPickerView = PvOptions.initOptionPicker(getContext(), new OnOptionsSelectListener() {
                            @Override
                            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                                binding.farrowType.setText(farrowingMethodList.get(options1));
                                clFzData.setFarrowType(options1);
                            }
                        });
                        optionsPickerView.setPicker(farrowingMethodList);
                        optionsPickerView.show();
                        break;
                }
            }
        };
        binding.collectionDate.setText(LocalDate.now().toString());
        binding.farrowingDate.setText(LocalDate.now().toString());
        getView().findViewById(R.id.farrowingMethodRelativeLayout).setOnClickListener(noDoubleClickListener);
        getView().findViewById(R.id.farrowingDateRelativeLayout).setOnClickListener(noDoubleClickListener);
        getView().findViewById(R.id.collectionDateRelativeLayout).setOnClickListener(noDoubleClickListener);
        getView().findViewById(R.id.submit).setOnClickListener(noDoubleClickListener);
        getView().findViewById(R.id.addTv).setOnClickListener(noDoubleClickListener);
    }

    public void setData() {
        // 使用数据绑定设置值到 ClFzData 对象
        clFzData.setCollectLocation(binding.collectLocation.getText().toString());
        clFzData.setFarrowDate(binding.farrowingDate.getText().toString());
        clFzData.setHouseNo(binding.houseNo.getText().toString());
        // 从 ViewAddHead 布局获取视图
        clFzData.setPigCode(binding.pigCode.getText().toString());
        clFzData.setPigBreed(binding.pigBreed.getText().toString());
        clFzData.setCollectDate(binding.collectionDate.getText().toString());

        clFzData.setCollector(binding.collector.getText().toString());
        clFzData.setTotalBorn(parseInt(binding.totalBorn.getText().toString()));
        clFzData.setLiveBorn(parseInt(binding.liveBorn.getText().toString()));
        clFzData.setPenNo(binding.penNumber.getText().toString());
        // 获取整数类型的数据
        clFzData.setBirthWeanWeight(parseBigDecimal(binding.birthWeanWeight.getText().toString()));
        clFzData.setPigCode(binding.pigCode.getText().toString());
        clFzData.setWeakPiglet(parseInt(binding.weakPiglet.getText().toString()));
        clFzData.setAbnormal(parseInt(binding.abnormal.getText().toString()));
        clFzData.setMummified(parseInt(binding.mummified.getText().toString()));
        clFzData.setDeadPiglet(parseInt(binding.deadPiglet.getText().toString()));
        clFzData.setLive12h(parseInt(binding.live12h.getText().toString()));
        clFzData.setLive24h(parseInt(binding.live24h.getText().toString()));
        clFzData.setLive7d(parseInt(binding.live7d.getText().toString()));
        clFzData.setWeanWeight(parseBigDecimal(binding.weanWeight.getText().toString()));
        clFzData.setWeanPiglets(parseInt(binding.weanPiglets.getText().toString()));
        clFzData.setRearedPiglets(parseInt(binding.rearedPiglets.getText().toString()));
        clFzData.setWeight21d(parseBigDecimal(binding.weight21d.getText().toString()));
        clFzData.setWeight60d(parseBigDecimal(binding.weight60d.getText().toString()));
        clFzData.setTeatLeft(parseInt(binding.teatLeft.getText().toString()));
        clFzData.setTeatRight(parseInt(binding.teatRight.getText().toString()));
        clFzData.setTeatTotal(parseInt(binding.teatTotal.getText().toString()));
        clFzData.setHealthyPiglets(parseInt(binding.healthyPiglets.getText().toString()));
        clFzData.setBirthWeight(parseBigDecimal(binding.birthWeight.getText().toString()));
        clFzData.setSurvivalRate(parseBigDecimal(binding.survivalRate.getText().toString()));
        clFzData.setFirstFarrowAge(parseInt(binding.firstFarrowAge.getText().toString()));
        clFzData.setParity(parseInt(binding.parity.getText().toString()));


    }

    public void getData() {
        setData();
        if (type.equals("post")) {
            List<ClFzData> list = new ArrayList<>();
            list.add(clFzData);
            RetrofitClient.getClient().create(ApiService.class).postFzData("繁殖性状-新增", list)
                    .enqueue(new ApiCallback(new ApiCallbackOnResponse() {
                        @Override
                        public void onResponse(Object v) {
                            FzDataObject fzDataListBean = (FzDataObject) v;
                            upData(fzDataListBean);
                        }
                    }));
        } else {
            RetrofitClient.getClient().create(ApiService.class).putFzData("繁殖性状-修改", clFzData)
                    .enqueue(new ApiCallback(new ApiCallbackOnResponse() {
                        @Override
                        public void onResponse(Object v) {
                            FzDataObject fzDataListBean = (FzDataObject) v;
                            upData(fzDataListBean);
                        }
                    }));
        }

    }

    public void upData(FzDataObject fzDataListBean) {
        if (fzDataListBean.isSucceeded()) {
            Bundle bundle = new Bundle();
            bundle.putLong("id", (type.equals("post") ? fzDataListBean.getData() : clFzData.getId()));
            bundle.putString("titleName", VeinRouter.REPRODUCTIVEDETAILS.getTitle());
            toFragmentPage(VeinRouter.REPRODUCTIVEDETAILS.setBundle(bundle));
            getActivity().finish();
        }
    }

    private int parseInt(String input) {
        try {
            return Integer.parseInt(input);
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    private BigDecimal parseBigDecimal(String input) {
        try {
            return new BigDecimal(input);
        } catch (NumberFormatException e) {
            return BigDecimal.ZERO;
        }
    }
}